package com.example.chcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chcrm.entity.common.OperateRecord;
import com.example.chcrm.entity.common.RandomHelper;
import com.example.chcrm.entity.common.ResponseMsg;
import com.example.chcrm.entity.common.ServletUtils;
import com.example.chcrm.entity.employee.EmployeeVo;
import com.example.chcrm.entity.supplier.HighwaySupplierCar;
import com.example.chcrm.entity.supplier.HighwaySupplierInfo;
import com.example.chcrm.mapper.HighwaySupplierCarMapper;
import com.example.chcrm.mapper.HighwaySupplierInfoMapper;
import com.example.chcrm.mapper.OperateRecordMapper;
import com.example.chcrm.service.HighwaySupplierCarService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author 邹
 * @Date 2025/4/20 23:39
 * @Version 1.0
 */
@Service
public class HighwaySupplierCarServiceImpl <T> implements HighwaySupplierCarService<T> {
    @Autowired
    private HighwaySupplierInfoMapper highwaySupplierInfoMapper;
    @Autowired
    private HighwaySupplierCarMapper highwaySupplierCarMapper;
    @Autowired
    private OperateRecordMapper operateRecordMapper;

    @Override
    public ResponseMsg<IPage<HighwaySupplierCar>> pageList(HighwaySupplierCar customerInfo, EmployeeVo empVo) {
        QueryWrapper<HighwaySupplierCar> query = new QueryWrapper<>();
        if(StringUtils.isNotBlank(customerInfo.getFleetId())){
            query.like("fleet_id",customerInfo.getFleetId());
        }
        if(StringUtils.isNotBlank(customerInfo.getDriverName())){
            query.like("driver_name",customerInfo.getDriverName());
        }
        if(customerInfo.getIsEnable() != null){
            query.eq("isEnable",customerInfo.getIsEnable());
        }
        if(customerInfo.getStatus() != null){
            query.eq("status",customerInfo.getStatus());
        }
        query.eq("is_deleted",0);
        query.orderByDesc("create_time");
        List<HighwaySupplierCar> list = highwaySupplierCarMapper.selectList(query);
        ResponseMsg<IPage<HighwaySupplierCar>> iPageResponseMsg = new ResponseMsg<>();
        Page<HighwaySupplierCar> page = new Page<>();
        page.setRecords(list);
        page.setTotal(list.size());
        page.setSize(customerInfo.getRows());
        page.setCurrent(customerInfo.getPage());
        iPageResponseMsg.setData(page);
        iPageResponseMsg.success("查询成功");
        return iPageResponseMsg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> add(HighwaySupplierCar carInfo, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();

        // 参数校验（已通过JSR 303注解校验，此处可移除重复校验）

        // 检查车牌号是否已存在（唯一性校验）
        Long licenseCount = highwaySupplierCarMapper.selectCount(new QueryWrapper<HighwaySupplierCar>()
                .eq("license", carInfo.getLicense())
                .eq("is_deleted", 0));
        if (licenseCount > 0) {
            msg.fail("车牌号已存在");
            return msg;
        }

        // 检查供应商是否存在
        Long fleetCount = highwaySupplierInfoMapper.selectCount(new QueryWrapper<HighwaySupplierInfo>()
                .eq("id", carInfo.getFleetId())
                .eq("is_deleted", 0));
        if (fleetCount == 0) {
            msg.fail("所属供应商不存在");
            return msg;
        }
        String  fleeName = highwaySupplierInfoMapper.selectById(carInfo.getFleetId()).getName();
        carInfo.setFleetName(fleeName);
        // 设置默认值
        carInfo.setId(RandomHelper.uuid());
        carInfo.setIsDeleted(0);
        carInfo.setCreateTime(new Date());
        carInfo.setAuditStatus(0); // 审核状态默认待审核
        carInfo.setStatus(HighwaySupplierCar.STATE_00); // 出车状态默认空闲中
        carInfo.setIsEnable(1); // 默认启用

        // 保存车辆信息
        int result = highwaySupplierCarMapper.insert(carInfo);
        if (result > 0) {
            // 添加操作记录
            OperateRecord operateRecord = new OperateRecord();
            operateRecord.setId(RandomHelper.uuid());
            operateRecord.setOperateType(OperateRecord.OPE_ADD);
            operateRecord.setSourceId(carInfo.getId());
//            operateRecord.setRemark("新增");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            operateRecord.setCreateTime(sdf.format(new Date()));
            operateRecordMapper.insert(operateRecord);
            msg.success("新增成功");
        } else {
            msg.fail("新增失败");
        }
        return msg;
    }

    @Override
    public ResponseMsg<Object> detail(String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        HighwaySupplierCar customerInfo = highwaySupplierCarMapper.selectById(id);
        if (customerInfo != null) {
            // 查询操作记录
            List<OperateRecord> operateRecords = operateRecordMapper.selectList(new QueryWrapper<OperateRecord>()
                    .eq("sourceId", customerInfo.getId())
                    .orderByDesc("create_time"));
            customerInfo.setOperateRecordList(operateRecords);
        }
        msg.setData(customerInfo);
        msg.success("查询成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> disable(HighwaySupplierCar essEmployee, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(essEmployee.getId())){
            msg.fail("未找到选中车辆");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        UpdateWrapper updateWrapper=  new UpdateWrapper<HighwaySupplierCar>();
        String  res ="";
        if (essEmployee.getIsEnable()==1){
            updateWrapper.set("isEnable",1);
            updateWrapper.eq("id",essEmployee.getId());
            highwaySupplierCarMapper.update(null,updateWrapper);
            res ="启用成功";
        }else if(essEmployee.getIsEnable()==0) {
            updateWrapper.set("isEnable", 0);
            updateWrapper.eq("id", essEmployee.getId());
            highwaySupplierCarMapper.update(null, updateWrapper);
            res = "禁用成功";
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            msg.fail("本次操作失败");
            return msg;
        }
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ope.setCreateTime(sdf.format(new Date()));
        ope.setOperateType("修改状态");
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        ope.setSourceId(essEmployee.getId());
        operateRecordMapper.insert(ope);
        msg.success(res);
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> update(HighwaySupplierCar customerInfo, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(customerInfo.getFleetId())) {
            msg.fail("未找到要修改的所属供应商");
            return msg;
        }
        HighwaySupplierInfo newInfo = highwaySupplierInfoMapper.selectOne(
                new QueryWrapper<HighwaySupplierInfo>().eq("id",customerInfo.getFleetId()));

        HighwaySupplierCar newCar = highwaySupplierCarMapper.selectOne(
             new QueryWrapper<HighwaySupplierCar>()  .eq("license", customerInfo.getLicense()) // 根据车牌号查询
                     .ne("id", customerInfo.getId()) );
        if (newInfo ==null){
            msg.fail("修改的供应商未找到");
            return msg;
        }
        if (newCar !=null){
            msg.fail("修改的车辆信息已存在");
            return msg;
        }
        String  fleeName = highwaySupplierInfoMapper.selectById(customerInfo.getFleetId()).getName();
        customerInfo.setFleetName(fleeName);
        // 更新数据
        int result = highwaySupplierCarMapper.updateById(customerInfo);
        if (result > 0) {
            // 添加操作记录
            OperateRecord operateRecord = new OperateRecord();
            operateRecord.setId(RandomHelper.uuid());
            operateRecord.setOperateType(OperateRecord.OPE_UPDATE);
            operateRecord.setSourceId(customerInfo.getId());
            operateRecord.setRemark("修改");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            operateRecord.setCreateTime(sdf.format(new Date()));

            if (empVo != null) {
                operateRecord.setOperationId(empVo.getId());
                operateRecord.setOperationName(empVo.getEmpNm());
            }

            operateRecordMapper.insert(operateRecord);
            msg.success("修改成功");
        } else {
            msg.fail("修改失败");
        }
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> badCar(HighwaySupplierCar essEmployee, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(essEmployee.getId())){
            msg.fail("未找到选中公路供应商");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        UpdateWrapper updateWrapper=  new UpdateWrapper<HighwaySupplierCar>();
        String  res ="";
        if (essEmployee.getStatus()==2){
            updateWrapper.set("status",2);
            updateWrapper.eq("id",essEmployee.getId());
            highwaySupplierCarMapper.update(null,updateWrapper);
            res ="故障成功";
        }else if(essEmployee.getStatus()==0) {
            updateWrapper.set("status", 0);
            updateWrapper.eq("id", essEmployee.getId());
            highwaySupplierCarMapper.update(null, updateWrapper);
            res = "解除故障成功";
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            msg.fail("本次操作失败");
            return msg;
        }
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ope.setCreateTime(sdf.format(new Date()));
        ope.setOperateType("修改故障状态");
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        ope.setSourceId(essEmployee.getId());
        operateRecordMapper.insert(ope);
        msg.success(res);
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> delete(HighwaySupplierCar customerCarModel, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        int deleteInt = highwaySupplierCarMapper.update(null, new UpdateWrapper<HighwaySupplierCar>().set("is_deleted",-1)
                .eq("id",customerCarModel.getId()));
        if (deleteInt>0){
                // 添加操作记录
                OperateRecord operateRecord = new OperateRecord();
                operateRecord.setId(RandomHelper.uuid());
                operateRecord.setOperateType(OperateRecord.OPE_UPDATE);
                operateRecord.setSourceId(customerCarModel.getId());
                operateRecord.setRemark("删除");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                operateRecord.setCreateTime(sdf.format(new Date()));

                if (empVo != null) {
                    operateRecord.setOperationId(empVo.getId());
                    operateRecord.setOperationName(empVo.getEmpNm());
                }

                operateRecordMapper.insert(operateRecord);
                msg.success("删除成功");
                return msg;
            }
        msg.fail("删除失败");
        return msg;
        }
}

